(function ($) {
	nsbase.controls.pageBar = PageBarFunc;

	function PageBarFunc (config) {
			var _self  = this;
            // 客户端分页时使用
            _self.showData = showData;

            var _defalut ={
                container:"",
                remote:false,
                actionUrl:"",
                actionParams:{},
                pageSize:20,
                pageHandler:null //function(){}
            }

            var _config,
                _results,
                _resultCount,
                _pageCount = 0, 
                _pageIndex = 1;

			var CLS_DISABLE = 'disabled';
            var numberHolder = "{$number}",
                selectedHolder = "{$selected}",
                resultKey = "results",
                resultCountKey = "totalCount",
                clientResults,
                ALL_SHOW_LIMIT_COUNT = 5, 
                RANGE_SHOW_LIMIT_COUNT = 2;
            var $pageTpl = $('<div class="grid-pagging-bar">\
                                <div class="bar-btn">\
                                    <a href="javascript:void(0);" class="prev">&nbsp;</a>\
                                    <div class="page-number-container"></div>\
                                    <a href="javascript:void(0);" class="next">&nbsp;</a>\
                                 </div>\
                            </div>');
            var numberPageTpl = '<a class="page-number '+ selectedHolder +'" href="javascript:void(0);">'+ numberHolder +'</a>'
            var btnPrev = $pageTpl.find("a.prev"),
                btnNext = $pageTpl.find("a.next"),
                pageNumberContainer = $pageTpl.find(".page-number-container");

            function init(){
                _config = $.extend({}, _defalut, config);
                
                _config.container.find(".grid-pagging-bar").remove();
                _config.container.append($pageTpl);
                bindHandler();
                if(_config.remote){
                    loadData();
                }
            }

            init();

            function loadData () {
                var actionParams = _config.actionParams;
                actionParams.pageIndex = _pageIndex;
                actionParams.pageSize = _config.pageSize;
                _config.container.mask();
                $.ajax({
                    cache: false,
                    url: _config.actionUrl,
                    contentType:"application/json",
                    dataType: "json",
                    type: "POST",
                    data: JSON.stringify(actionParams),
                    success: function (data, textStatus, XMLHttpRequest) {
                        _config.container.unmask();
                        /*if(!data){
                                data = {};
                                data[resultKey] = [];
                                data[resultCountKey] =0;
                            }
                            _results = data[resultKey] || [];
                            _resultCount = data[resultCountKey] || 0;
                            _pageCount = parseInt(_resultCount / _config.pageSize);
                            if(_resultCount % _config.pageSize !== 0){
                                _pageCount +=1;
                            }
                            onPagging();
                         */
                        if(data.success){
                            if(!data && data.data){
                                data = {};
                                data[resultKey] = [];
                                data[resultCountKey] =0;
                            }
                            _results = data.data[resultKey] || data.data;
                            _resultCount = data.data[resultCountKey] || 0;
                            _pageCount = parseInt(_resultCount / _config.pageSize);
                            if(_resultCount % _config.pageSize !== 0){
                                _pageCount +=1;
                            }
                            if(_config.pageHandler){
                                _config.pageHandler(_results);
                            }
                            syncState();
                        } else {
                            _config.container.unmask();
                            alert(data.message);
                        }
                       
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert("error");
                    }
                });
            }

            // 客户端分页
            function showData (results) {
                if(!results || results.length == 0){
                    return;
                }
                clientResults = results;
                _resultCount = clientResults.length;
                _pageCount = parseInt(_resultCount / _config.pageSize);
                if(_resultCount % _config.pageSize !== 0){
                    _pageCount +=1;
                }
                onPagging();
            }

            function bindHandler () {
                $pageTpl.delegate('.page-number', 'click', function (event) {
                    event.preventDefault();
                    var sender = $(this);
                    if(sender.hasClass("selected")) return false;
                    _pageIndex = parseInt(sender.text());
                    onPagging();
                });

                btnPrev.click(function(){
                    if($(this).hasClass(CLS_DISABLE)) return false;
                    _pageIndex --;
                    onPagging();
                });
                btnNext.click(function(){
                    if($(this).hasClass(CLS_DISABLE)) return false;
                    _pageIndex ++;
                    onPagging();
                });
            }
            
            function onPagging(){
                if(_config.remote){
                    loadData();
                } else {
                    _results = getPagedResult();
                }
                if(_config.pageHandler){
                    _config.pageHandler(_results);
                }
                syncState();
            }

            // 客户端分页
            function getPagedResult(){
                if(clientResults && clientResults.length > 0){
                    var startIndex = (_pageIndex- 1) * _config.pageSize;
                    var endIndex = startIndex + _config.pageSize;
                    return clientResults.slice(startIndex, endIndex);
                } 
                return null;
            }

            function getNumberPages () {
                var pageItems = [];
                if(_pageCount == 1){
                    addPageItem(1,1);
                    return pageItems.join('');
                }

                if (_pageCount <= ALL_SHOW_LIMIT_COUNT) {//show all pages number
                    curMax = _pageCount;
                    addPageItem(1, _pageCount);
                } else {//show begin with 1
                    var startNum = (_pageIndex <= ALL_SHOW_LIMIT_COUNT) ? 1 : (_pageIndex - RANGE_SHOW_LIMIT_COUNT),
                        lastLimit = _pageIndex + RANGE_SHOW_LIMIT_COUNT,
                        endNum = lastLimit < _pageCount ? (lastLimit > ALL_SHOW_LIMIT_COUNT ? lastLimit : ALL_SHOW_LIMIT_COUNT) : _pageCount;
                    if (startNum > 1) {
                        addPageItem(1, 1);
                        addEllipsis();
                    }
                    curMax = endNum;
                    addPageItem(startNum, endNum);
                }
                if (curMax < _pageCount) {
                    addEllipsis();
                    addPageItem(_pageCount, _pageCount);
                }
                
                function addPageItem (from,to) {
                    for (var i = from; i <= to; i++) {
                        var template;
                        if(i===_pageIndex){
                            template = numberPageTpl.replace(numberHolder,i).replace(selectedHolder,"selected");
                        } else {
                            template = numberPageTpl.replace(numberHolder,i).replace(selectedHolder,"");
                        }
                        pageItems.push(template);
                    }
                }

                function addEllipsis() {
                    var template = '<em class="number-ellipsis">...</em>';
                    pageItems.push(template);
                }

                return pageItems.join('');
            }

            function syncState () {
                pageNumberContainer.empty();
                var numberpage = getNumberPages();
                pageNumberContainer.append(numberpage);

                enableButton([btnPrev,btnNext],true);
                if(_pageIndex==1){
                   enableButton([btnPrev],false);
                }
                if(_pageIndex == _pageCount || _pageCount === 0){
                    enableButton([btnNext],false);
                }
            }

            function enableButton(buttons, enable) {
	            $.each(buttons,function(index,$button){
	                if(enable){
	                    $button.removeClass(CLS_DISABLE);
	                } else{
	                    $button.addClass(CLS_DISABLE);
	                }
	            });
        	}
    }
})(jQuery);